#include "toggleTrick.h"


//--------------------------------------------------------------
void toggleTrick::setup(){
	sprintf(name, "toggle");
	bTakeSnapshot = false;
	bHaveBlobs = false;
	meAsGray.allocate(320,240);
	meAndedWithHand.allocate(320,240);
	bUncovered = false;
	bShow = false;
}


//--------------------------------------------------------------
void toggleTrick::reset(){
	bHaveBlobs = false;
	bUncovered = false;
	bShow = false;
	meAndedWithHand.set(0);
	meAsGray.set(0);
}

//--------------------------------------------------------------
void toggleTrick::update(){
	
	
	if (bTakeSnapshot == true){
		vbd->takeSnapshot();
		if (vbd->nBlobs > 0){
			memcpy(&blob,&vbd->vidBlob, sizeof(videoBlob));
			bHaveBlobs = true;
		}
		bTakeSnapshot = false;
		bUncovered = false;
		bShow = true;
	}
	
	meAsGray.set(0);
	meAndedWithHand.set(0);
	
	if (bHaveBlobs == true){
		//blob.angle = ofRandom(0,TWO_PI);
		blob.update();
		blob.draw(meAsGray, 255);
		meAndedWithHand = meAsGray;
		meAndedWithHand &= vhd->handDetectionImage;
		
		
		int meCount = meAsGray.countNonZeroInRegion(0,0,width, height);
		int andCount = meAndedWithHand.countNonZeroInRegion(0,0,width, height);
		
		if (meCount == andCount){
			nFramesCovered++;
			//bUncovered = false;
			if (bUncovered == true && nFramesCovered > 10){
				bShow = !bShow;
				bUncovered = false;
			}
		} else {
			nFramesCovered = 0;
		}
		
		if (andCount == 0){
			bUncovered = true;
		}
	}
	
}

//--------------------------------------------------------------
void toggleTrick::draw(){
	if (bHaveBlobs == true){
		if (bShow == true){
			 blob.draw();
		} else {
			ofEnableAlphaBlending();
			ofSetColor(255,0,0,155);
			if (bDrawDiagnostically) blob.drawOutline();
			ofDisableAlphaBlending();
		}
	}
	
	ofSetColor(255,255,255);
	//meAsGray.draw(0,0);	
	//meAndedWithHand.draw(0,240);
}


//--------------------------------------------------------------
void toggleTrick::keyPressed(int key){
	if (key == 's'){
		bTakeSnapshot = true;
	} else if (key == ' '){
		reset();
	}
}